package _interview150;

import java.util.Arrays;

/**
 * 289. 生命游戏
 */
public class No289 {
    private int[][] board;
    private int m, n;
    private int[][] ans;

    public void gameOfLife(int[][] board) {
        this.board = board;
        m = board.length;
        n = board[0].length;
        this.ans = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                change(i, j);
            }
        }
        for (int i = 0; i < m; i++) {
            if (n >= 0) System.arraycopy(ans[i], 0, this.board[i], 0, n);
        }
    }

    private void change(int row, int column) {
        int curSumAlive = 0;
        for (int i = Math.max(row - 1, 0); i <= Math.min(row + 1, m - 1); i++) {
            for (int j = Math.max(column - 1, 0); j <= Math.min(column + 1, n - 1); j++) {
                curSumAlive += board[i][j];
            }
        }
        if (board[row][column] == 1) {
            curSumAlive--;
            if (curSumAlive == 2 || curSumAlive == 3) ans[row][column] = 1;
        } else if (curSumAlive == 3) ans[row][column] = 1;
    }
}
